<?php

$childId=[];
for($i=0;$i<10;$i++){
    $pid=pcntl_fork();
    if($pid == -1){
        die("cant not fork\n");
    }
    if($pid){
        //主进程
        $childId[]=$pid;
    }
    else{
        //子进程代码
        $nowpid=posix_getpid();
        $seconds=rand(5,30);
        echo "process {$nowpid} was created and do something,and sleep {$seconds}".PHP_EOL;
        dosomething($nowpid,$seconds);
        exit();
    }

}

while(count($childId)>0){
    foreach($childId as $key=>$kpid){
        $res=pcntl_waitpid($kpid,$status,WNOHANG);
        if($res == -1 || $res>0){
            unset($childId[$key]);
            echo "sub process:{$kpid} exited with {$status}".PHP_EOL;
        }
    }
}

function dosomething($pid,$seconds){
    file_put_contents("./log/".$pid.".txt",$pid.PHP_EOL,FILE_APPEND);
    sleep($seconds);
}